package cn.jinjimi.app.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;

import cn.jinjimi.app.AppContext;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.store.entity.custom.ContactInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Roy
 * Date: 2017/2/5
 */

public class AddressUtils {

    /**
     * 读取通讯录中联系人的id、name、phones、birthday
     *
     * @return
     */
    public static List<Custom> findAll(Context mContext) {
        List<Custom> contacts = new ArrayList<>();
        ContentResolver contentResolver = mContext.getContentResolver();
        Cursor cursor = null;
        cursor = contentResolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                null,
                null,
                null,
                ContactsContract.Contacts.DISPLAY_NAME
                        + " COLLATE LOCALIZED ASC");

        if (cursor == null)
            return contacts;

        try {

            if (cursor.moveToFirst()) {
                do {
                    // 获得联系人的ID号
                    int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    // 获得联系人姓名
                    String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    List<ContactInfo> phones = new ArrayList<>();
                    Cursor phoneCr = null;
                    phoneCr = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                                    + contactId, null, null);
                    List<String> tempP = new ArrayList<String>();
                    //取得电话号码

                    if (phoneCr != null && phoneCr.moveToFirst()) {
                        do {
                            String number = phoneCr.getString(phoneCr.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            int phoneType = phoneCr.getInt(phoneCr.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                            if (!tempP.contains(number)) {
                                phones.add(new ContactInfo(phoneType, number));
                                tempP.add(number);
                            }
                        } while (phoneCr.moveToNext());
                        phoneCr.close();
                    }

                /* 没有电话号码时不添加 */
                    if (phones.size() == 0) {
                        continue;
                    }

                    // 获取联系人备注
                    String selectionNote = ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE
                            + "'"
                            + " and "
                            + ContactsContract.CommonDataKinds.Event.CONTACT_ID + " = " + contactId;
                    Cursor cursorNote = mContext.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                            null, selectionNote, null, null);
                    String remark = "";
                    if (cursorNote != null && cursorNote.moveToFirst()) {
                        String mimetype = cursorNote.getString(cursorNote.getColumnIndex(ContactsContract.Data.MIMETYPE)); // 取得mimetype类型,扩展的数据都在这个类型里面
                        if (ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE.equals(mimetype)) {
                            remark = cursorNote.getString(cursorNote.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                        }
                        cursorNote.close();
                    }

                    // 获取联系人地址信息
                    String selectionAddr = ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE
                            + "'"
                            + " and "
                            + ContactsContract.CommonDataKinds.Event.CONTACT_ID + " = " + contactId;
                    Cursor cursorAddr = mContext.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                            null, selectionAddr, null, null);
                    String addr = "";
                    if (cursorAddr != null && cursorAddr.moveToFirst()) {
                        String mimetype = cursorAddr.getString(cursorAddr.getColumnIndex(ContactsContract.Data.MIMETYPE));
                        if (ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE.equals(mimetype)) {
                            addr = cursorAddr.getString(cursorAddr.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));

//                        int postalType = cursorAddr.getInt(cursorAddr.getColumnIndex(StructuredPostal.TYPE));
//                        // 住宅通讯地址
//                        if (postalType == StructuredPostal.TYPE_HOME) {
//                            String homeStreet = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.STREET));
//                            String homeCity = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.CITY));
//                            String homeBox = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POBOX));
//                            String homeArea = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.NEIGHBORHOOD));
//                            String homeState = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.REGION));
//                            String homeZip = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POSTCODE));
//                            String homeCountry = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.COUNTRY));
//                        }
//                        // 单位通讯地址
//                        if (postalType == StructuredPostal.TYPE_WORK) {
//                            String street = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.STREET));
//                            String ciry = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.CITY));
//                            String box = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POBOX));
//                            String area = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.NEIGHBORHOOD));
//                            String state = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.REGION));
//                            String zip = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POSTCODE));
//                            String country = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.COUNTRY));
//                        }
//                        // 其他通讯地址
//                        if (postalType == StructuredPostal.TYPE_OTHER) {
//                            String otherStreet = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.STREET));
//                            String otherCity = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.CITY));
//                            String otherBox = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POBOX));
//                            String otherArea = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.NEIGHBORHOOD));
//                            String otherState = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.REGION));
//                            String otherZip = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.POSTCODE));
//                            String otherCountry = cursorAddr.getString(cursorAddr.getColumnIndex(StructuredPostal.COUNTRY));
//                        }
                        }
                        cursorAddr.close();
                    }

                    //获取联系人生日
                    String[] projection = new String[]{ContactsContract.CommonDataKinds.Event.DATA1};
                    String selection = ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
                            + "'"
                            + " and "
                            + ContactsContract.CommonDataKinds.Event.TYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY
                            + "'"
                            + " and "
                            + ContactsContract.CommonDataKinds.Event.CONTACT_ID
                            + " = " + contactId;
                    Cursor birthdayCursor = mContext.getContentResolver().query(
                            ContactsContract.Data.CONTENT_URI,
                            projection,
                            selection,
                            null,
                            null);
                    String birthday = "";
                    if (birthdayCursor != null && birthdayCursor.moveToFirst()) {
                        birthday = birthdayCursor.getString(birthdayCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.DATA));
                        birthdayCursor.close();
                    }

                    Custom contact = new Custom(contactName, birthday);
                    contact.contanct_id = (contactId);
                    contact.contactInfos = (phones);
                    contact.remark = (remark);
                    contact.address = (addr);

                    contacts.add(contact);
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
            return contacts;
        }
    }

    /**
     * 根据本地通讯录中 id 生成头像文件
     *
     * @param contactId
     * @return
     */
    public static File getFileImage(long contactId) {
        //获取头像
        ContentResolver contentResolver = AppContext.getInstance().getContentResolver();
        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
        Bitmap bmp_head = BitmapFactory.decodeStream(input);

        if (bmp_head == null) return null;

        String fileName = "xrk_c_" + System.currentTimeMillis() + new Random().nextLong() + ".png";
        File f = new File(Environment.getExternalStorageDirectory() + "/temp/", fileName);
        File dirFile = f.getParentFile();
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bmp_head.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            return f;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bmp_head != null && !bmp_head.isRecycled()) {
                bmp_head.recycle();
            }
        }
        return null;
    }
}
